export default class Tool {
	// 节流
	static throttle (fn, delay) {
		let timer = null;
		let starTime = new Date();
		return () => {
			let curTime = new Date();
			clearInterval(timer);
			// 规定的时间触发，不然用户一直操作就一直不会触发
			if (curTime - starTime >= delay) {
				starTime = curTime;
				fn();
			} else {
				timer = setTimeout(fn, delay);
			}
		};
	}

	// 防抖
	static debounce (fn, delay) {
		let timer = null;
		return () => {
			clearInterval(timer);
			timer = setTimeout(fn, delay);
		};
	}

	// 路由转map对象
	static routesToMap (asyncRoutes, routesMap = {}) {
		asyncRoutes.forEach(item => {
			let temp = { ...item };
			if (item.children && item.children.length > 0) {
				delete temp.children;
				routesMap[item.path] = temp;
				this.routesToMap(item.children, routesMap);
			} else {
				routesMap[item.path] = temp;
			}
		});
		return routesMap;
	}

	// 映射路由表
	static mappingRoutes (tree, routesMap, parentPath) {
		tree.forEach(item => {
			const menu = item.permissionMenu;
			// 优先取接口字段
			const temp = routesMap[menu.menuUrl];
			temp.meta.title = item.name || temp.meta.title;
			temp.meta.icon = menu.menuIcon || temp.meta.icon;
			item.meta = temp.meta;
			item.component = temp.component;
			parentPath && (menu.menuUrl = parentPath + '/' + menu.menuUrl);
			item.path = menu.menuUrl;
			if (item.children && item.children.length > 0) {
				this.mappingRoutes(item.children, routesMap, menu.menuUrl);
			}
		});
		return tree;
	}

	// 路由过滤
	static filterAsyncRoutes (routes, roles) {
		const res = [];
		routes.forEach(route => {
			const tmp = { ...route };
			if (this.hasPermission(roles, tmp)) {
				if (tmp.children) {
					tmp.children = this.filterAsyncRoutes(tmp.children, roles);
				}
				res.push(tmp);
			}
		});

		return res;
	}

	// 权限校验
	static hasPermission (roles, route) {
		if (route.meta && route.meta.roles && route.meta.roles.length > 0) {
			return roles.some(role => route.meta.roles.includes(role));
		} else {
			return true;
		}
	}

	// 后缀名
	static extension (str) {
		return str.substring(str.lastIndexOf('.') + 1);
	}

	// 提取金额最多2个小数
	static getAmount (digitalStr) {
		return digitalStr.replace(/^\D*([1-9]\d*\.?\d{1,2})?.*$/, '$1');
	}

	// 获取上一个月时间
	static getPreMonth (date) {
		var d = new Date(date);
		d.setMonth(d.getMonth() - 1);
		return d;
	}

		/**
	 * @description userName => user_name
	 * @param {string} key
	 * @return {string} newKey
	 */
	static humpToLine (key){
		return key.replace(/([A-Z])/g, a => `_${a.toLocaleLowerCase()}`);
	}

	/**
	 * @description user_name => userName
	 * @param {string} key
	 * @return {string} newKey
	 */
	static lineTohump (key){
		return key.replace(/_(\w)/g, ([,$2]) => `${$2.toUpperCase()}`);
	}

	// 大写金额转换
	static chMoneyToDigitalMoney (payload){
		let moneyMap ={
			'零' : '0',
			'壹' : '1',
			'贰' : '2',
			'叁' : '3',
			'肆' : '4',
			'伍' : '5',
			'陆' : '6',
			'柒' : '7',
			'捌' : '8',
			'玖' : '9',
			'拾' : '0',
			'佰' : '00',
			'仟' : '000',
			'万' : '0000',
			'亿' : '00000000',
			'兆' : '000000000000'
		};
		let chMoneyParams = '';
		let chMoney = Object.keys(moneyMap);
		Array.from(payload).forEach(item=>{
			if (chMoney.includes(item)){
				chMoneyParams = chMoneyParams+item;
			}
		});
		let moneyArr = [];
		Array.from(chMoneyParams).forEach(item=>{
			moneyArr.push(moneyMap[item]);
		});
		return moneyArr.join(',').replace(/,/ig,'');
	}

	// OCR金额识别转换
	static extractMoney (payload){
		let isWan = payload.includes('万');
		let money =parseFloat(payload.replace(/,/,''));
		if (isWan){
			let moneyArr = String(money).split('.');
			money = '';
			money = moneyArr[0]+'0000';
			if (moneyArr.length===2){
				money+='.'+moneyArr[1];
			}
		}
		return money;
	}

	// 流文件下载
	static fileDdownload (data) {
		let blob = new Blob([data], { type : 'application/vnd.ms-excel;charset=UTF-8' });
		let url = window.URL.createObjectURL(blob);
		let aLink = document.createElement('a');
		aLink.style.display = 'none';
		aLink.href = url;
		aLink.setAttribute('download', 'filename');
		document.body.appendChild(aLink);
		aLink.click();
		document.body.removeChild(aLink);
		window.URL.revokeObjectURL(url);
	}
	// form文件下载
	static fileDdownloada (url) {
		var dlform = document.createElement('form');
		dlform.style = 'display:none;';
		dlform.method = 'post';
		dlform.action = url;
		dlform.target = 'callBackTarget';
		var hdnFilePath = document.createElement('input');
		hdnFilePath.type = 'hidden';
		hdnFilePath.name = 'filePath';
		hdnFilePath.value = 'filename';
		dlform.appendChild(hdnFilePath);
		document.body.appendChild(dlform);
		dlform.submit();
		document.body.removeChild(dlform);
	}

}



var chnNumChar = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
var chnUnitSection = ['', '万', '亿', '万亿', '亿亿']
var chnUnitChar = ['', '十', '百', '千']
// 节内转换算法：
function SectionToChinese (section) {
  var strIns = ''
  var chnStr = ''
  var unitPos = 0
  var zero = true
  while (section > 0) {
    var v = section % 10
    if (v === 0) {
      if (!zero) {
        zero = true
        chnStr = chnNumChar[v] + chnStr
      }
    } else {
      zero = false
      strIns = chnNumChar[v]
      strIns += chnUnitChar[unitPos]
      chnStr = strIns + chnStr
    }
    unitPos++
    section = Math.floor(section / 10)
  }
  return chnStr
}

/**
 * 转换算法主函数：
 * @param {Number} num 数字金额
 * @returns 大写金额如:(一百)
 */
function NumberToChinese (num) {
  var unitPos = 0
  var strIns = ''; var
    chnStr = ''
  var needZero = false

  if (num === 0) {
    return chnNumChar[0]
  }

  while (num > 0) {
    var section = num % 10000
    if (needZero) {
      chnStr = chnNumChar[0] + chnStr
    }
    strIns = SectionToChinese(section)
    strIns += (section !== 0) ? chnUnitSection[unitPos] : chnUnitSection[0]
    chnStr = strIns + chnStr
    needZero = (section < 1000) && (section > 0)
    num = Math.floor(num / 10000)
    unitPos++
  }

  return chnStr
}

console.log(NumberToChinese('13500'))
var chnNumChar = {
  零: 0,
  一: 1,
  二: 2,
  三: 3,
  四: 4,
  五: 5,
  六: 6,
  七: 7,
  八: 8,
  九: 9
}
var chnNameValue = {
  十: { value: 10, secUnit: false },
  百: { value: 100, secUnit: false },
  千: { value: 1000, secUnit: false },
  万: { value: 10000, secUnit: true },
  亿: { value: 100000000, secUnit: true }
}
/**
 *
 * @param {String} chnStr 大写金额如:(一百)
 * @returns 数字金额如:(100)
 */
function ChineseToNumber (chnStr) {
  var rtn = 0
  var section = 0
  var number = 0
  var secUnit = false
  var str = chnStr.split('')
  for (var i = 0; i < str.length; i++) {
    var num = chnNumChar[str[i]]
    if (typeof num !== 'undefined') {
      number = num
      if (i === str.length - 1) {
        section += number
      }
    } else {
      var unit = chnNameValue[str[i]].value
      secUnit = chnNameValue[str[i]].secUnit
      if (secUnit) {
        section = (section + number) * unit
        rtn += section
        section = 0
      } else {
        section += (number * unit)
      }
      number = 0
    }
  }
  return rtn + section
}

console.log(ChineseToNumber('一万三千五百'))


/** 大写表 */
let chineseNumber = {
  '壹': 1,
  '贰': 2,
  '叁': 3,
  '肆': 4,
  '伍': 5,
  '陆': 6,
  '柒': 7,
  '捌': 8,
  '玖': 9
}

/** 金额单位 */
let chineseUnit = {
  '亿': 100000000,
  '万': 10000,
  '仟': 1000,
  '佰': 100,
  '拾': 10,
  '元': 1,
  '角': 0.1,
  '分': 0.01
}

/**
 * 中文大写数字转换
 * @param {String} chinese 贰佰元人民币
 * @returns 200
 */
let chineseToNumber = (chinese) => {
  let result = 0
  /** 匹配单位 */
  const groupReg = /([零|壹|贰|叁|肆|伍|陆|柒|捌|玖|仟|佰|拾]+[亿|万|元|角|分])/g
  /** 匹配单位数字 */
  const numberReg = /([壹|贰|叁|肆|伍|陆|柒|捌|玖][仟|佰|拾]?)/g
  /** 分组：[xx亿，xx万，xx元，xx角，xx分] */
  const groupResult = Array.isArray(chinese.match(groupReg)) ? chinese.match(groupReg) : []
  groupResult.forEach(strUnits => {
    /** 分组单位：亿，万，元，角，分 */
    const groupUnit = chineseUnit[strUnits.substr(-1, 1)]
    const numberResult = Array.isArray(strUnits.match(numberReg)) ? strUnits.match(numberReg) : []
    /** 组 匹配数字：[六百，二十，三] */
    numberResult.forEach((strUnit) => {
      const number = chineseNumber[strUnit.substr(0, 1)]
      const unit = chineseUnit[strUnit.substr(1, 2)] || 1
      /** 结果累加 */
      result += number * unit * groupUnit
    })
  })
  return result
}
console.log(chineseToNumber('贰佰柒拾捌万零伍佰元人民币'))
